package com.maixun.lib_comment.ui

import android.widget.Toast
import com.alibaba.android.arouter.launcher.ARouter
import com.maixun.lib_base.ui.activity.BaseActivityImpl
import com.maixun.lib_comment.ARouterConstance
import com.maixun.lib_base.ServerCode
import com.maixun.lib_base.mvp.BaseContract
import com.maixun.lib_base.utils.LogUtils
import com.maixun.lib_comment.ui.dialog.InvalidationDialog
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener

/**
 * @author:Lmoumou
 * @date:2020/7/30
 * 描述:
 **/
abstract class BaseMVPActivity<P : BaseContract.BasePresenter> : BaseActivityImpl(),
    BaseContract.BaseView ,OnRefreshLoadMoreListener{

    companion object {
        private const val TAG = "BaseMVPActivity"
    }

    protected abstract val mPresenter: P

    override fun showLoading() {

    }

    override fun dismissLoading() {
    }

    /**
     * 数据异常
     * */
    override fun onDataAnalyzeEx(e: Throwable) {
        LogUtils.e(TAG, "${e.message}")
    }

    /**
     * 接口请求异常
     * */
    override fun onNetEx(e: Throwable) {
        LogUtils.e(TAG, "${e.message}")
    }

    override fun onToast(msg: String?) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
    }

    /**
     * 处理与服务端约定的Code码
     *
     * @param msg   服务端返回的信息
     * @param serverCode    服务端返回的Code码
     * */
    override fun onServerCode(msg: String?, serverCode: String) {
        when (serverCode) {
            ServerCode.NO_TOKEN,
            ServerCode.TOKEN_INVALID,
            ServerCode.TOKEN_ERROR -> {
                //重新登录
                InvalidationDialog {
                    //跳转到登录界面
                    ARouter.getInstance().build(ARouterConstance.LOGIN.URL_ENTER_WAY).navigation()
                    this.finish()
                }.showThis(
                    supportFragmentManager,
                    InvalidationDialog::class.java.simpleName
                )
            }
            ServerCode.NO_PERMISSION -> {
                //权限弹窗
            }
            ServerCode.USER_DATA_NOT_COMPLETE -> {
                //完善资料
            }
            ServerCode.EXCEPTION -> {
                //报Toast信息
            }
            else -> {//未约定的Code码
                onToast(msg)
            }
        }
    }

    open fun initRefreshView(refreshView: SmartRefreshLayout) {
        refreshView.setOnRefreshLoadMoreListener(this)
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {

    }

    override fun onRefresh(refreshLayout: RefreshLayout) {

    }

    override fun onDestroy() {
        super.onDestroy()
        mPresenter.detachView()
    }
}